package com.lego.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lego.bean.OrderDTO;
import com.lego.bean.Orders;
import com.lego.bean.PersonalOrdersVO;
import com.lego.service.GoodsService;
import com.lego.service.OrdersService;
import com.lego.service.UserService;
import com.lego.service.impl.GoodsServiceImpl;
import com.lego.service.impl.OrdersServiceImpl;
import com.lego.service.impl.UserServiceImpl;

@WebServlet("/selectUserOrders.do")
public class SelcetUserOrdersServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        OrdersService ods = new OrdersServiceImpl();
        request.setCharacterEncoding("utf-8");
        
        // 1. 获取参数
        String orderStatus = request.getParameter("orderStatus");
        int userId = getIntParameter(request, "userId", 0);
        int pageNum = getIntParameter(request, "pageNum", 1);
        int pageSize = getIntParameter(request, "pageSize", 12);
        
        // 2. 调用Service（返回OrderDTO列表）
        List<OrderDTO> orderDTOList = ods.selectUserOrders(orderStatus, userId, pageNum, pageSize);
        
        int totalRows = ods.selectUserRows(orderStatus, userId);
        
        PersonalOrdersVO<OrderDTO> vo = new PersonalOrdersVO<>(
            orderDTOList, 
            pageNum, 
            pageSize, 
            orderStatus, 
            totalRows
        );
        
        response.setContentType("application/json;charset=utf-8");
        new ObjectMapper().writeValue(response.getWriter(), vo);
    }
    
    private int getIntParameter(HttpServletRequest request, String name, int defaultValue) {
        try {
            return Integer.parseInt(request.getParameter(name));
        } catch (Exception e) {
            return defaultValue;
        }
    }
}


